'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Grid,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  Chip,
  Avatar,
  Tab,
  Tabs,
  Divider,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  ListItemSecondaryAction,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Snackbar,
  Alert,
  Fab,
  MenuItem,
  IconButton,
} from '@mui/material';
import Navbar from '@/components/Navbar';
import BusinessIcon from '@mui/icons-material/Business';
import PersonIcon from '@mui/icons-material/Person';
import SearchIcon from '@mui/icons-material/Search';
import FilterListIcon from '@mui/icons-material/FilterList';
import AddIcon from '@mui/icons-material/Add';
import SendIcon from '@mui/icons-material/Send';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import VisibilityIcon from '@mui/icons-material/Visibility';
import { useRouter } from 'next/navigation';
import { fetchCurrentUser } from '@/services/authService';

// 模拟数据 - 合作需求
const cooperationNeeds = [
  {
    id: 1,
    title: '寻找AI技术合作伙伴',
    company: '未来科技有限公司',
    type: '技术合作',
    description: '我们正在寻找在计算机视觉和深度学习领域有经验的合作伙伴',
    tags: ['AI', '深度学习', '计算机视觉'],
    contact: '张总',
    date: '2024-02-18',
  },
  {
    id: 2,
    title: '新能源项目投资机会',
    company: '绿色能源集团',
    type: '投资合作',
    description: '光伏发电站建设项目，寻找投资合作伙伴',
    tags: ['新能源', '光伏', '投资'],
    contact: '李总',
    date: '2024-02-17',
  },
];

// 模拟数据 - 校友资源
const alumniResources = [
  {
    id: 1,
    name: '王教授',
    title: 'AI研究专家',
    organization: '清华大学',
    expertise: ['人工智能', '机器学习'],
    description: '在AI领域有20年研究经验，可提供技术咨询',
  },
  {
    id: 2,
    name: '张总',
    title: '投资总监',
    organization: '创新投资基金',
    expertise: ['投资', '企业管理'],
    description: '专注于科技创新企业投资，可提供融资对接',
  },
];

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ py: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

export default function ResourcesPage() {
  const router = useRouter();
  const [tabValue, setTabValue] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isCompanyAdmin, setIsCompanyAdmin] = useState(false);
  const [user, setUser] = useState<any>(null);
  
  // 对话框状态
  const [contactDialogOpen, setContactDialogOpen] = useState(false);
  const [selectedResource, setSelectedResource] = useState<any>(null);
  const [messageContent, setMessageContent] = useState('');
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');
  
  // 发布需求对话框
  const [publishDialogOpen, setPublishDialogOpen] = useState(false);
  const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
  const [passwordInput, setPasswordInput] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [newNeed, setNewNeed] = useState({
    title: '',
    type: '技术合作',
    description: '',
    tags: '',
  });

  // 我的需求列表
  const [myNeeds, setMyNeeds] = useState<any[]>([]);
  const [loadingMyNeeds, setLoadingMyNeeds] = useState(false);
  
  // 登录提示对话框
  const [loginDialogOpen, setLoginDialogOpen] = useState(false);
  const [loginRedirect, setLoginRedirect] = useState('');

  useEffect(() => {
    // 检查用户登录状态
    const token = localStorage.getItem('token');
    if (!token) {
      setIsLoggedIn(false);
      return;
    }

    // 获取用户信息
    fetchUserInfo();
    
    // 尝试恢复保存的页面状态
    try {
      const savedPageState = localStorage.getItem('resourcesPageState');
      if (savedPageState) {
        const parsedState = JSON.parse(savedPageState);
        console.log('恢复保存的页面状态:', parsedState);
        
        // 恢复标签页和搜索条件
        if (parsedState.tabValue !== undefined) {
          setTabValue(parsedState.tabValue);
        }
        
        if (parsedState.searchTerm) {
          setSearchTerm(parsedState.searchTerm);
        }
        
        // 清除已恢复的状态，避免重复使用
        localStorage.removeItem('resourcesPageState');
      }
      
      // 检查是否是从登录页面返回的
      const lastVisitedPage = localStorage.getItem('lastVisitedPage');
      if (lastVisitedPage === '/enterprise/resources') {
        console.log('检测到从登录页面返回，刷新状态');
        localStorage.removeItem('lastVisitedPage');
        
        // 显示欢迎回来的消息
        setSnackbarMessage('登录成功，欢迎回来！');
        setSnackbarSeverity('success');
        setSnackbarOpen(true);
      }
    } catch (e) {
      console.error('恢复页面状态失败:', e);
    }
  }, []);

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      // 从localStorage中尝试获取缓存的用户数据
      const cachedUserData = localStorage.getItem('userData');
      if (cachedUserData) {
        try {
          const parsedUserData = JSON.parse(cachedUserData);
          console.log('从缓存读取用户数据:', parsedUserData.username);
          // 先使用缓存的数据快速设置状态
          setUser(parsedUserData);
          setIsLoggedIn(true);
          setIsCompanyAdmin(parsedUserData.is_company_admin || false);
        } catch (e) {
          console.error('缓存的用户数据解析失败:', e);
          // 清除无效缓存
          localStorage.removeItem('userData');
        }
      }

      // 无论是否有缓存数据，都请求最新的用户信息
      const token = localStorage.getItem('token');
      if (!token) {
        setIsLoggedIn(false);
        return;
      }

      // 使用封装好的用户信息获取服务
      const result = await fetchCurrentUser({
        onRetry: (retryCount) => {
          console.log(`获取用户信息重试中 (${retryCount}/3)...`);
        }
      });

      if (!result.success) {
        // 处理不同的错误情况
        if (result.error === 'no_token' || result.error === 'unauthorized') {
          localStorage.removeItem('token');
          localStorage.removeItem('userData'); // 清除缓存的用户数据
          setIsLoggedIn(false);
          return;
        } else {
          // 其他错误情况
          console.error('获取用户信息失败:', result.message);
          
          // 如果已经有缓存数据，那么继续使用它
          if (cachedUserData) {
            console.log('使用缓存数据并保持登录状态');
            return; // 已经设置了用户数据，保持登录状态
          }
          
          setIsLoggedIn(false);
          return;
        }
      }

      console.log('用户信息获取成功:', result.user.username);
      setUser(result.user);
      setIsLoggedIn(true);
      setIsCompanyAdmin(result.user.is_company_admin || false);
      
      // 更新缓存的用户数据
      localStorage.setItem('userData', JSON.stringify(result.user));
      
      // 如果是企业管理员，获取我的需求列表
      if (result.user.is_company_admin) {
        fetchMyNeeds(token);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果已经有缓存数据，保持登录状态
      if (user) {
        console.log('发生错误但使用现有用户数据保持登录状态');
        return;
      }
      setIsLoggedIn(false);
    }
  };

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const handleOpenContactDialog = (resource: any) => {
    console.log('尝试打开联系对话框, 登录状态:', isLoggedIn);
    console.log('当前用户:', user ? user.username : '未登录');
    
    const token = localStorage.getItem('token');
    if (!token) {
      console.log('无token，需要登录');
      // 未登录，显示登录对话框并设置重定向参数
      setLoginRedirect('/enterprise/resources');
      setLoginDialogOpen(true);
      return;
    }
    
    if (!isLoggedIn) {
      // 二次检查：有token但状态显示未登录
      console.log('有token但状态未登录，尝试刷新登录状态');
      
      // 尝试从localStorage获取用户数据
      const cachedUserData = localStorage.getItem('userData');
      if (cachedUserData) {
        try {
          const userData = JSON.parse(cachedUserData);
          console.log('从缓存恢复用户数据:', userData.username);
          setUser(userData);
          setIsLoggedIn(true);
          setIsCompanyAdmin(userData.is_company_admin || false);
          
          // 继续打开对话框
          setSelectedResource(resource);
          setContactDialogOpen(true);
          return;
        } catch (e) {
          console.error('解析缓存用户数据失败');
        }
      }
      
      // 如果没有缓存数据，提示登录并更新状态
      setLoginRedirect('/enterprise/resources');
      setLoginDialogOpen(true);
      return;
    }

    // 一切正常，打开对话框
    setSelectedResource(resource);
    setContactDialogOpen(true);
  };

  const handleCloseContactDialog = () => {
    setContactDialogOpen(false);
    setSelectedResource(null);
    setMessageContent('');
  };

  const handleSendMessage = async () => {
    if (!selectedResource || !messageContent.trim()) return;

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        console.log('发送消息时检测到未登录状态');
        setLoginRedirect('/enterprise/resources');
        setLoginDialogOpen(true);
        return;
      }

      // 二次检查登录状态和用户信息
      if (!isLoggedIn || !user) {
        console.log('发送消息时状态显示未登录，但有token，尝试恢复状态');
        
        // 尝试从localStorage恢复用户数据
        const cachedUserData = localStorage.getItem('userData');
        if (cachedUserData) {
          try {
            const userData = JSON.parse(cachedUserData);
            console.log('从缓存恢复用户数据:', userData.username);
            // 恢复用户状态
            setUser(userData);
            setIsLoggedIn(true);
            
            // 继续发送消息
            console.log('用户状态已恢复，继续发送消息');
          } catch (e) {
            console.error('解析缓存用户数据失败，取消发送消息');
            setLoginRedirect('/enterprise/resources');
            setLoginDialogOpen(true);
            return;
          }
        } else {
          console.log('无缓存用户数据，取消发送消息');
          setLoginRedirect('/enterprise/resources');
          setLoginDialogOpen(true);
          return;
        }
      }

      console.log('开始发送消息，接收者:', selectedResource.id || selectedResource.name);
      
      // 如果没有接收者ID，生成一个临时ID（仅用于演示或测试）
      const recipientId = selectedResource.id || Math.floor(Math.random() * 1000 + 1);

      // 注意：收件箱API已经被删除，这里使用模拟实现
      // 模拟发送消息成功
      console.log('模拟发送消息:', {
        recipientId,
        content: messageContent,
        subject: `资源对接: ${user?.company || user?.username} 联系您`,
      });
      
      // 模拟API响应延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 显示成功消息
      setSnackbarMessage('消息已成功发送！（注意：收件箱功能已移除，此为模拟操作）');
      setSnackbarSeverity('success');
      setSnackbarOpen(true);
      
      // 关闭对话框
      handleCloseContactDialog();
    } catch (error) {
      console.error('发送消息失败:', error);
      setSnackbarMessage('发送消息失败，请稍后再试');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
    }
  };

  const handlePublishNeed = () => {
    if (!isLoggedIn) {
      setSnackbarMessage('请先登录后再操作');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
      return;
    }

    if (!isCompanyAdmin) {
      setSnackbarMessage('只有企业负责人才能发布需求');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
      return;
    }

    // 打开密码验证对话框
    setPasswordDialogOpen(true);
  };
  
  const handlePasswordVerification = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setSnackbarMessage('登录状态已失效，请重新登录');
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
        return;
      }
      
      // 验证密码
      const response = await fetch('/api/auth/verify-password', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          password: passwordInput
        })
      });
      
      const data = await response.json();
      
      if (response.ok && data.success) {
        // 密码验证成功，关闭密码对话框，打开发布需求对话框
        setPasswordDialogOpen(false);
        setPasswordInput('');
        setPasswordError('');
        setPublishDialogOpen(true);
      } else {
        // 密码验证失败
        setPasswordError(data.message || '密码验证失败');
      }
    } catch (error) {
      console.error('密码验证失败:', error);
      setPasswordError('验证过程中发生错误，请重试');
    }
  };

  const handleClosePasswordDialog = () => {
    setPasswordDialogOpen(false);
    setPasswordInput('');
    setPasswordError('');
  };

  const handleClosePublishDialog = () => {
    setPublishDialogOpen(false);
    setNewNeed({
      title: '',
      type: '技术合作',
      description: '',
      tags: '',
    });
  };

  const handleSubmitNeed = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setSnackbarMessage('登录状态已失效，请重新登录');
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
        return;
      }

      // 发布需求
      const response = await fetch('/api/enterprise/resources/needs', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ...newNeed,
          tags: newNeed.tags.split(',').map(tag => tag.trim()),
        })
      });

      if (!response.ok) {
        throw new Error('发布需求失败');
      }

      // 显示成功消息
      setSnackbarMessage('需求已成功发布');
      setSnackbarSeverity('success');
      setSnackbarOpen(true);
      
      // 关闭对话框
      handleClosePublishDialog();
      
      // 刷新需求列表
      fetchMyNeeds(token);
    } catch (error) {
      console.error('发布需求失败:', error);
      setSnackbarMessage('发布需求失败，请稍后再试');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
    }
  };

  // 获取我的需求列表
  const fetchMyNeeds = async (token: string) => {
    try {
      setLoadingMyNeeds(true);
      const response = await fetch('/api/enterprise/resources/my-needs', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.ok) {
        const data = await response.json();
        setMyNeeds(data.needs || []);
      }
    } catch (error) {
      console.error('获取需求列表失败:', error);
    } finally {
      setLoadingMyNeeds(false);
    }
  };

  // 编辑需求
  const handleEditNeed = (need: any) => {
    setNewNeed({
      title: need.title,
      type: need.type,
      description: need.description,
      tags: need.tags.join(','),
    });
    setPublishDialogOpen(true);
  };
  
  // 删除需求
  const handleDeleteNeed = async (needId: number) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setSnackbarMessage('登录状态已失效，请重新登录');
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
        return;
      }
      
      const response = await fetch(`/api/enterprise/resources/needs/${needId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        throw new Error('删除需求失败');
      }
      
      // 显示成功消息
      setSnackbarMessage('需求已成功删除');
      setSnackbarSeverity('success');
      setSnackbarOpen(true);
      
      // 刷新需求列表
      fetchMyNeeds(token);
    } catch (error) {
      console.error('删除需求失败:', error);
      setSnackbarMessage('删除需求失败，请稍后再试');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
    }
  };

  // 处理登录对话框关闭
  const handleCloseLoginDialog = () => {
    setLoginDialogOpen(false);
  };

  // 跳转到登录页面
  const handleGoToLogin = () => {
    // 确保有一个有效的重定向URL
    const redirectPath = loginRedirect || '/enterprise/resources';
    
    // 在localStorage中存储当前状态，以便登录后恢复
    try {
      localStorage.setItem('lastVisitedPage', redirectPath);
      
      // 存储其他可能需要的状态数据
      const pageState = {
        tabValue,
        searchTerm
      };
      localStorage.setItem('resourcesPageState', JSON.stringify(pageState));
      
      console.log('保存页面状态，准备跳转到登录页');
    } catch (e) {
      console.error('保存页面状态失败:', e);
    }
    
    router.push(`/login?redirect=${encodeURIComponent(redirectPath)}`);
  };

  return (
    <>
      
      {/* 头部区域 */}
      <Box
        sx={{
          bgcolor: 'primary.main',
          color: 'white',
          py: 4,
          backgroundImage: 'linear-gradient(45deg, #1976d2 30%, #1565c0 90%)',
        }}
      >
        <Container maxWidth="lg">
          <Typography variant="h4" component="h1" gutterBottom>
            资源对接大厅
          </Typography>
          <Typography variant="subtitle1" gutterBottom>
            连接优质校友资源，促进商业合作
          </Typography>
          <Box sx={{ mt: 4, display: 'flex', gap: 2 }}>
            <TextField
              fullWidth
              variant="outlined"
              placeholder="搜索合作机会或校友资源"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              sx={{ 
                bgcolor: 'white',
                borderRadius: 1,
                '& .MuiOutlinedInput-root': {
                  '& fieldset': {
                    borderColor: 'transparent',
                  },
                },
              }}
              InputProps={{
                startAdornment: <SearchIcon sx={{ mr: 1, color: 'grey.500' }} />,
              }}
            />
            <Button
              variant="contained"
              color="secondary"
              startIcon={<FilterListIcon />}
            >
              筛选
            </Button>
          </Box>
        </Container>
      </Box>

      {/* 主要内容区域 */}
      <Container maxWidth="lg" sx={{ my: 4 }}>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={tabValue} onChange={handleTabChange}>
            <Tab label="合作需求" />
            <Tab label="校友资源" />
            {isLoggedIn && isCompanyAdmin && <Tab label="我的需求" />}
          </Tabs>
        </Box>

        <TabPanel value={tabValue} index={0}>
          <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 2 }}>
            <Button
              variant="contained"
              color="primary"
              startIcon={<AddIcon />}
              onClick={handlePublishNeed}
            >
              发布需求
            </Button>
          </Box>
          
          <Grid container spacing={3}>
            {cooperationNeeds.map((need) => (
              <Grid item xs={12} key={need.id}>
                <Card>
                  <CardContent>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <Box>
                        <Typography variant="h6" gutterBottom>
                          {need.title}
                        </Typography>
                        <Typography color="text.secondary" gutterBottom>
                          {need.company} · {need.type}
                        </Typography>
                      </Box>
                      <Typography color="text.secondary">
                        发布日期：{need.date}
                      </Typography>
                    </Box>
                    <Typography paragraph>
                      {need.description}
                    </Typography>
                    <Box sx={{ mb: 2 }}>
                      {need.tags.map((tag) => (
                        <Chip
                          key={tag}
                          label={tag}
                          size="small"
                          sx={{ mr: 1 }}
                        />
                      ))}
                    </Box>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography variant="body2">
                        联系人：{need.contact}
                      </Typography>
                      <Button 
                        variant="contained" 
                        color="primary"
                        onClick={() => handleOpenContactDialog(need)}
                      >
                        联系对接
                      </Button>
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        </TabPanel>

        <TabPanel value={tabValue} index={1}>
          <List>
            {alumniResources.map((resource) => (
              <ListItem
                key={resource.id}
                alignItems="flex-start"
                component={Card}
                sx={{ mb: 2 }}
              >
                <ListItemAvatar>
                  <Avatar>
                    <PersonIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Typography variant="h6">
                        {resource.name}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {resource.title}
                      </Typography>
                      <Divider orientation="vertical" flexItem />
                      <Typography variant="body2" color="text.secondary">
                        {resource.organization}
                      </Typography>
                    </Box>
                  }
                  secondary={
                    <Box sx={{ mt: 1 }}>
                      <Typography paragraph>
                        {resource.description}
                      </Typography>
                      <Box>
                        {resource.expertise.map((exp) => (
                          <Chip
                            key={exp}
                            label={exp}
                            size="small"
                            sx={{ mr: 1 }}
                          />
                        ))}
                      </Box>
                    </Box>
                  }
                />
                <ListItemSecondaryAction>
                  <Button 
                    variant="contained" 
                    color="primary"
                    onClick={() => handleOpenContactDialog(resource)}
                  >
                    联系对接
                  </Button>
                </ListItemSecondaryAction>
              </ListItem>
            ))}
          </List>
        </TabPanel>
        
        {/* 我的需求面板 */}
        {isLoggedIn && isCompanyAdmin && (
          <TabPanel value={tabValue} index={2}>
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 2 }}>
              <Button
                variant="contained"
                color="primary"
                startIcon={<AddIcon />}
                onClick={handlePublishNeed}
              >
                发布新需求
              </Button>
            </Box>
            
            {loadingMyNeeds ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
                <Typography>加载中...</Typography>
              </Box>
            ) : myNeeds.length === 0 ? (
              <Box sx={{ textAlign: 'center', my: 4 }}>
                <Typography variant="body1" color="text.secondary">
                  您还没有发布过需求，点击"发布新需求"按钮开始创建
                </Typography>
              </Box>
            ) : (
              <Grid container spacing={3}>
                {myNeeds.map((need) => (
                  <Grid item xs={12} key={need.id}>
                    <Card>
                      <CardContent>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                          <Box>
                            <Typography variant="h6" gutterBottom>
                              {need.title}
                            </Typography>
                            <Typography color="text.secondary" gutterBottom>
                              {need.type}
                            </Typography>
                          </Box>
                          <Box>
                            <Typography color="text.secondary">
                              发布日期：{new Date(need.created_at).toLocaleDateString()}
                            </Typography>
                            <Box sx={{ display: 'flex', gap: 1, mt: 1 }}>
                              <IconButton 
                                size="small" 
                                color="primary"
                                onClick={() => handleEditNeed(need)}
                              >
                                <EditIcon />
                              </IconButton>
                              <IconButton 
                                size="small" 
                                color="error"
                                onClick={() => handleDeleteNeed(need.id)}
                              >
                                <DeleteIcon />
                              </IconButton>
                            </Box>
                          </Box>
                        </Box>
                        <Typography paragraph>
                          {need.description}
                        </Typography>
                        <Box sx={{ mb: 2 }}>
                          {need.tags.map((tag: string) => (
                            <Chip
                              key={tag}
                              label={tag}
                              size="small"
                              sx={{ mr: 1 }}
                            />
                          ))}
                        </Box>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Typography variant="body2" color={need.is_active ? 'success.main' : 'text.secondary'}>
                            状态：{need.is_active ? '已发布' : '未发布'}
                          </Typography>
                          <Button 
                            variant="outlined" 
                            color="primary"
                            startIcon={<VisibilityIcon />}
                          >
                            查看联系记录
                          </Button>
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            )}
          </TabPanel>
        )}
      </Container>
      
      {/* 联系对接对话框 */}
      <Dialog open={contactDialogOpen} onClose={handleCloseContactDialog} maxWidth="sm" fullWidth>
        <DialogTitle>
          联系{selectedResource?.name || selectedResource?.contact}
        </DialogTitle>
        <DialogContent>
          <DialogContentText sx={{ mb: 2 }}>
            发送消息至{selectedResource?.name || selectedResource?.contact}的收件箱，对方会收到通知。
          </DialogContentText>
          <TextField
            autoFocus
            margin="dense"
            id="message"
            label="消息内容"
            fullWidth
            multiline
            rows={4}
            variant="outlined"
            value={messageContent}
            onChange={(e) => setMessageContent(e.target.value)}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseContactDialog}>取消</Button>
          <Button 
            onClick={handleSendMessage} 
            variant="contained" 
            color="primary" 
            startIcon={<SendIcon />}
            disabled={!messageContent.trim()}
          >
            发送
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 发布需求对话框 */}
      <Dialog open={publishDialogOpen} onClose={handleClosePublishDialog} maxWidth="sm" fullWidth>
        <DialogTitle>发布合作需求</DialogTitle>
        <DialogContent>
          <DialogContentText sx={{ mb: 2 }}>
            填写以下信息，发布您的合作需求。
          </DialogContentText>
          <TextField
            autoFocus
            margin="dense"
            id="title"
            label="需求标题"
            fullWidth
            variant="outlined"
            value={newNeed.title}
            onChange={(e) => setNewNeed({...newNeed, title: e.target.value})}
            sx={{ mb: 2 }}
          />
          <TextField
            select
            margin="dense"
            id="type"
            label="需求类型"
            fullWidth
            variant="outlined"
            value={newNeed.type}
            onChange={(e) => setNewNeed({...newNeed, type: e.target.value})}
            sx={{ mb: 2 }}
          >
            <MenuItem value="技术合作">技术合作</MenuItem>
            <MenuItem value="投资合作">投资合作</MenuItem>
            <MenuItem value="市场合作">市场合作</MenuItem>
            <MenuItem value="人才需求">人才需求</MenuItem>
            <MenuItem value="其他">其他</MenuItem>
          </TextField>
          <TextField
            margin="dense"
            id="description"
            label="需求描述"
            fullWidth
            multiline
            rows={4}
            variant="outlined"
            value={newNeed.description}
            onChange={(e) => setNewNeed({...newNeed, description: e.target.value})}
            sx={{ mb: 2 }}
          />
          <TextField
            margin="dense"
            id="tags"
            label="标签（用逗号分隔）"
            fullWidth
            variant="outlined"
            value={newNeed.tags}
            onChange={(e) => setNewNeed({...newNeed, tags: e.target.value})}
            helperText="例如：AI, 深度学习, 投资"
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClosePublishDialog}>取消</Button>
          <Button 
            onClick={handleSubmitNeed} 
            variant="contained" 
            color="primary"
            disabled={!newNeed.title || !newNeed.description}
          >
            发布
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 密码验证对话框 */}
      <Dialog open={passwordDialogOpen} onClose={handleClosePasswordDialog}>
        <DialogTitle>身份验证</DialogTitle>
        <DialogContent>
          <DialogContentText sx={{ mb: 2 }}>
            请输入您的密码以验证身份
          </DialogContentText>
          <TextField
            autoFocus
            margin="dense"
            id="password"
            label="密码"
            type="password"
            fullWidth
            variant="outlined"
            value={passwordInput}
            onChange={(e) => setPasswordInput(e.target.value)}
            error={!!passwordError}
            helperText={passwordError}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClosePasswordDialog}>取消</Button>
          <Button 
            onClick={handlePasswordVerification} 
            variant="contained" 
            color="primary"
            disabled={!passwordInput.trim()}
          >
            验证
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 提示消息 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={6000}
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={() => setSnackbarOpen(false)} 
          severity={snackbarSeverity}
          sx={{ width: '100%' }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>

      {/* 登录提示对话框 */}
      <Dialog
        open={loginDialogOpen}
        onClose={handleCloseLoginDialog}
      >
        <DialogTitle>需要登录</DialogTitle>
        <DialogContent>
          <DialogContentText>
            您需要登录后才能使用此功能
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseLoginDialog}>取消</Button>
          <Button 
            onClick={handleGoToLogin} 
            variant="contained" 
            color="primary"
          >
            去登录
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
} 